package cn.melonlib.specials.auth.comp.service;

import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import cn.melonlib.specials.auth.model.entity.Account;
import cn.melonlib.specials.auth.model.entity.Tenant;
import cn.melonlib.specials.auth.model.entity.TenantUser;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
public class UserService extends WorkerBasicService<TenantUser> {

    @Resource
    private AccountManagerService accountManagerService;

    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public TenantUser createUser(
             TenantUser user,
             List<String> userTypes,
             String tenant,
             String password)throws Exception{
        String validUser="from TenantUser where code=?1";
        @Language("HQL") String tenantQuery="from Tenant where code=?1";
        List<Tenant> tenantList=dao.<List<Tenant>,DefaultQuery>search(new DefaultQuery(tenantQuery,List.of(tenant))).getResult();
        List<TenantUser> users=dao.<List<TenantUser>, DefaultQuery>search(new DefaultQuery(validUser,List.of(user.getCode()))).getResult();
        if(users.size()>0){
            return null;
        }
        user=dao.save(user).getResult();
        Account account=new Account();
        account.setAccount(user.getCode());
        account.setActivated(true);
        account.setAccountTypes(getJsonMapper().writeValueAsString(userTypes));
//        account.setTenant(tenant);
        account.setTenantId(tenantList.get(0).getId());
        account.setTenantCode(tenant);
        accountManagerService.createAccount(account,password);
        return user;
    }
}
